#!/usr/bin/env python
from django.conf import settings
import time
import random
from . import models


def save_upload_file(f):
    _save_path = settings.UPLOAD_PATH
    filename = time.strftime('%Y%m%d%H%M%S', time.localtime()) + str(random.randrange(1000,9999)) + "." + f.content_type.split('/')[1]
    #print(filename)
    with open(_save_path + "/" + filename, 'wb+') as upfile:
        for file in f.chunks(1024):
            upfile.write(file)

    return "uploads/" + filename


def format_common_dict(common_obj_list):
    return_value = []
    for common in common_obj_list:
        self_thumb_up_count = models.Comment.objects.filter(article_id=common.article_id,
                                                            parent_comment_id=common.id,
                                                            comment_type=2).count()
        return_value.append({'id': common.id,
                             'img': common.user.head_img,
                             'pid': common.parent_comment_id,
                             'content': common.comment,
                             'author': common.user.name,
                             'pubdate': common.date,
                             'article_id': common.article_id,
                             'thumb_up_count': self_thumb_up_count})
    #print(return_value)
    return return_value
